<template>
  <div>
    <el-form :inline="true" :model="selectfrom">
      <el-form-item label="题目名称">
        <el-input size="default" v-model="like" clearable></el-input>
      </el-form-item>
      <el-form-item label="题目ID">
        <el-input size="default" v-model="selectfrom.ID" clearable></el-input>
      </el-form-item>
      <el-form-item class="">
        <el-button size="default" @click="start" type="primary" :icon="Search"> 查询 </el-button>
      </el-form-item>
    </el-form>
    <div class="">
      <div class="">
        <!-- <div class="font-size14 margin-bottom20">
          说明：团队题目是学生在系统 "团队题目" 页中可以看到的所有题目，您可以从公开题目、个人题目中添加题目到团队题目中
        </div> -->
        <el-table :data="tableData" border height="74vh" @sort-change="sortchange" @row-click="clickTableRow"
          row-class-name="cursor-pointer">
          <template v-slot:empty>
            <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
          </template>
          <el-table-column prop="ID" label="ID" width="100"></el-table-column>
          <el-table-column prop="name" label="name"></el-table-column>
          <el-table-column prop="type" sortable label="类型" width=""></el-table-column>
          <el-table-column prop="difficulty" sortable :formatter="difficultyFormat" label="难度" width="">
            <template #default="{ row, column }">
              <div v-if="row.difficulty" :class="`difficulty-${row.difficulty}`">
                {{ row.difficulty ? DATAdifficulty[row.difficulty] : '' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="label" label="标签" width="" show-overflow-tooltip
            :tooltip-formatter="({ row, column, cellValue }) => row.questionlabel.map(vo => label.find(e => e.ID === vo.labelid)?.name).join(', ')">
            <template #default="{ row, column }">
              <el-tag class="question-intable-label" text type="primary" effect="plain" size="default"
                v-for="(vo, keys) in row.questionlabel" v-text="label.find(e => e.ID === vo.labelid)?.name"
                :key="`1-${keys}`">
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="user.name" width="" label="创建者"></el-table-column>
          <el-table-column prop="createdAt" width="" sortable :formatter="({ createdAt }) => formatDate(createdAt)"
            label="创建时间">
          </el-table-column>
          <el-table-column prop="updatedAt" width="" sortable :formatter="({ updatedAt }) => formatDate(updatedAt)"
            label="更新时间">
          </el-table-column>
          <!-- <el-table-column prop="testcaseslength" label="测试点数量" width="">
            <template #default="{ row }">
              <router-link :to="{ name: '测试点', params: { ID: row.ID } }">
                {{ row.testcaseslength }}
              </router-link>
            </template>
          </el-table-column> -->
          <el-table-column prop="userquestionlength" label="答题记录" width=""></el-table-column>
          <el-table-column label="操作" fixed="right" width="110px">
            <template #default="{ row }">
              <router-link v-slot="{ navigate }" custom :to="{ name: '更新题目', query: { ID: row.ID } }">
                <el-button size="default" @click.stop="navigate" type="warning">修改</el-button>
              </router-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-pagination class="pager" :total="totalCount" :page-size="Number(limit)" :page-sizes="pageSizes"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total,sizes,prev, pager, next">
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElButton, ElInput, ElMessage, ElPagination, ElTable, ElTableColumn } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Iobj, Iquestionoption, asyncadminselectquestion, asyncselectquestion } from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { toLocaleString } from "../../../util/time";
import { DATAdifficulty } from "../../../index/data/data";
const route = useRoute()
const router = useRouter()
const store = useStore(Storekey);
const user = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});
const teamId = computed(() => {
  return Number(user.value?.teamid)
})
const sortable = ref<"DESC" | "ASC">("DESC");
const offset = ref(0);
const limit = ref(20); const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500]
const order = ref<keyof Studycodemodel.Iquestion>("ID");
const like = ref("");

const query = computed(() => {
  let _like: [keyof Studycodemodel.Iquestion, string | number] | undefined;
  const obj: Iobj<Iquestionoption> = {
    _limit: Number(limit.value),
    _offset: Number(offset.value),
    _order: order.value,
    _sortable: sortable.value,

    range: "match",
    type: "代码"
  };
  if (like.value) {
    _like = ['name', like.value];
  }
  const { info, ...w } = selectfrom;
  Object.assign(obj, w)

  if (info) {
    if (!_like) {
      _like = ["info", info];
    } else {
      obj.info = info;
    }
  }
  if (_like) {
    obj._like = _like;
  }
  return obj;
});
const selectfrom = reactive<Studycodemodel.Iquestion>({
  type: "代码"
});

const label = computed(() => {
  return store.state.label?.rows || [];
});

const tableData = ref<Studycodemodel.Iquestion[]>([]);
const totalCount = ref<number>(0);
async function start() {
  try {
    const { count, rows } = await asyncselectquestion(query.value) // sys 接口
    // const { count, rows } = await asyncadminselectquestion(query.value) // admin 接口
    tableData.value = rows
    totalCount.value = count
  } catch (e: any) {
    ElMessage.error(e);
  }
}
onMounted(() => {
  store.dispatch("actionlabel");
  start();
});

// formatter
function difficultyFormat(row: Studycodemodel.Iquestion) {
  return store.state.state?.difficulty[Number(row.difficulty - 1)]
}
function formatDate(date: Date) {
  return toLocaleString(date);
}
function handleCurrentChange(val: number) {
  offset.value = limit.value * (val - 1);
  start()
}
const handleSizeChange = (val: number) => {
  limit.value = val
  start()
}

function sortchange(row: {
  order: string;
  prop: keyof Studycodemodel.Iquestion;
}) {
  const { prop } = row;
  if (row.order == "descending") {
    sortable.value = "DESC";
  } else {
    sortable.value = "ASC";
  }
  order.value = prop;
}

const selectedRow = ref<Studycodemodel.Iquestion>();
function clickTableRow(row: Studycodemodel.Iquestion, column: any, event: Event): void {
  selectedRow.value = row
  // 题目详情
  router.push({ name: "题目详情", params: { ID: row.ID } });
}
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}

a {
  text-decoration: none;
}

.admin-main {
  overflow: auto;
}

.admin-container {
  height: 100%;
}

.margin-bottom20 {
  margin-bottom: 20px !important;
}

.font-size14 {
  font-size: 14px;
}

.question-intable-label {
  margin: 0 4px;
  padding: 0 10px;
  box-sizing: border-box;
  border-radius: 3px;
}

.question-intable-label {
  height: 28px;
}

.pager {
  margin-top: 20px;
  float: right;
}
</style>

<style></style>